<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="收货编号" prop="collectId">
        <el-input
          v-model="queryParams.collectId"
          placeholder="请输入收货编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="收货来源" prop="collectSource">-->
<!--        <el-select clearable v-model="queryParams.collectSource" size="small">-->
<!--          <el-option label="供应商" :value="1" />-->
<!--          <el-option label="用户" :value="2" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="供应商" prop="sourceId">
        <el-select v-model="queryParams.sourceId" clearable filterable remote :remote-method="remoteSupplier" size="small">
          <el-option
            v-for="supplier in supplierOptions"
            :key="supplier.supplierId"
            :label="supplier.supplierName"
            :value="supplier.supplierId"/>
        </el-select>
      </el-form-item>
      <el-form-item label="快递单号" prop="collectExpress">
        <el-input
          v-model="queryParams.collectExpress"
          placeholder="请输入快递单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="待生成" :value="1" />
          <el-option label="已生成" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          size="small"
          v-model="createTimeRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :unlink-panels="true"
          @change="createTimeChange"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['recovery:collect:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['recovery:collect:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExportByGoodsList(true)"
          v-hasPermi="['recovery:collect:export']"
        >导出详情</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="collectList" @selection-change="handleSelectionChange">
      <el-table-column label="收货编号" align="center" prop="collectId" />
<!--      <el-table-column label="收货来源" align="center" prop="collectSource" />-->
      <el-table-column label="供应商" align="center" prop="sourceName" width="180" show-overflow-tooltip />
      <el-table-column label="回收单号" align="center" prop="orderId" />
      <el-table-column label="收货数量" align="center" prop="collectNum" width="80" />
      <el-table-column label="价格组" align="center" prop="collectPrice" width="160" show-overflow-tooltip>
        <template v-slot="scope">
          <el-tooltip>
            <div slot="content">
              <div>{{scope.row.collectPrice}}</div>
              <div>合计: {{collectPriceTotal(scope.row)}}</div>
            </div>
            <div style="white-space: nowrap;overflow: hidden;cursor: pointer">{{scope.row.collectPrice}}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="快递单号" align="center" prop="collectExpress" width="130" show-overflow-tooltip />
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <el-tag v-if="scope.row.status === 1">待生成</el-tag>
          <el-tag v-else type="warning">已生成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="绿色回收" align="center" prop="hasGreen">
        <template v-slot="scope">
          <el-tag type="success" v-if="scope.row.hasGreen === 'y'">是</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template v-slot="scope">
          <el-button v-if="scope.row.collectSource === 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['recovery:collect:edit']"
          >修改</el-button>
          <el-button v-if="scope.row.status === 1"
            size="mini"
            type="text"
            icon="el-icon-circle-plus-outline"
            @click="handleAddGoodsList(scope.row)"
            v-hasPermi="['recovery:collect:create']"
          >生成</el-button>
          <el-button v-if="scope.row.status === 1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['recovery:collect:remove']"
          >删除</el-button>
          <el-button v-if="scope.row.status === 2"
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleDetail(scope.row)"
            v-hasPermi="['recovery:collect:detail']"
          >详情</el-button>
          <el-button v-if="scope.row.status === 2"
            size="mini"
            type="text"
            icon="el-icon-printer"
            @click="gotoPrinting(scope.row)"
          >打印</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="详情" :visible.sync="detailOpen" width="80%" append-to-body>
      <el-row>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExportByGoodsList(false)"
            v-hasPermi="['recovery:collect:export']"
          >导出</el-button>
        </el-col>
      </el-row>
      <el-table :data="recoveryGoodsList" border>
        <el-table-column label="商品编码" align="center" prop="goodsId" />
        <el-table-column label="商品型号" align="center" prop="goodsName" show-overflow-tooltip />
        <el-table-column label="打印内容" align="center" prop="printing" show-overflow-tooltip />
        <el-table-column label="成本价" align="center" prop="costPrice" />
        <el-table-column label="质检报告" align="center" prop="testInfo" show-overflow-tooltip />
      </el-table>
    </el-dialog>

    <!-- 添加或修改回收管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" :width="diaWidth" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div v-if="form.storeIds != null">
          <el-row>
            <el-col :span="12">
              <el-form-item label="供应商" prop="sourceId">
                <el-select v-model="form.sourceId" filterable remote clearable :remote-method="remoteSupplier" style="width: 100%">
                  <el-option
                    v-for="supplier in supplierOptions"
                    :key="supplier.supplierId"
                    :label="supplier.supplierName"
                    :value="supplier.supplierId"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="快递单号" prop="collectExpress">
                <el-input v-model="form.collectExpress" placeholder="请输入快递单号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-table v-loading="loading" :data="storeList" @selection-change="handleSelectionChange" :row-class-name="setRowClassName">
            <el-table-column label="回收编号" align="center" prop="storeId" />
            <el-table-column label="机型名称" align="center" prop="modelName" />
            <el-table-column label="机型串号" align="center" prop="modelSn" />
            <el-table-column label="公司信息" align="center" prop="companyInfo" />
            <el-table-column label="合计" align="center">
              <template slot-scope="scope">
                <span style="color: red">{{rowTotal(scope.row)}}</span>
              </template>
            </el-table-column>
            <el-table-column label="报价师" align="center" prop="offerName" :formatter="offerNameFormat" />
          </el-table>
        </div>
        <div v-else>
          <el-form-item label="绿色回收" prop="hasGreen">
            <el-radio-group v-model="form.hasGreen">
              <el-radio label="n">否</el-radio>
              <el-radio label="y">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="供应商" prop="sourceId">
            <el-select v-model="form.sourceId" filterable remote clearable :remote-method="remoteSupplier" style="width: 100%">
              <el-option
                v-for="supplier in supplierOptions"
                :key="supplier.supplierId"
                :label="supplier.supplierName"
                :value="supplier.supplierId"/>
            </el-select>
          </el-form-item>
          <el-form-item label="收货数量" prop="collectNum">
            <el-input-number v-model="form.collectNum" placeholder="请输入收货数量" :max="50" :min="1" :disabled="form.status === 2" />
          </el-form-item>
          <el-form-item label="价格组" prop="collectPrice">
            <el-input type="number" v-model="changePrice"
                      placeholder="请输入价格"
                      @keyup.enter.native="priceChange"
                      :disabled="form.status === 2"
            />
            <el-tag v-if="form.collectPrice != null" style="margin-right: 5px"
                    v-for="(price,index) in String(form.collectPrice).split(',')"
                    class="el-icon-error" @click="removePrice(index)">
              {{price}}
            </el-tag>
            <el-button v-if="form.collectPrice != null" type="danger" size="small" @click="form.collectPrice = null">清除</el-button>
          </el-form-item>
          <el-form-item label="快递单号" prop="collectExpress">
            <el-input v-model="form.collectExpress" placeholder="请输入快递单号" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <collect-add
      :open="addOpen"
      :row="addRow"
      :sup-format="supplierFormatter"
      @flush="getList"
      @close="addOpen = false"></collect-add>
  </div>
</template>

<script>
import { listCollect, getCollect, delCollect, addCollect, updateCollect, exportCollect,createGoodsList, listCollectNumber } from "@/api/recovery/collect";
import {listSupplier} from "@/api/basic/supplier"
import {listUser} from "@/api/system/user"
import {listGoods, exportGoods} from "@/api/recovery/goods"
import {selectListByIds} from "@/api/store/collect";
import collectAdd from "@/views/recovery/collect/collect-add";
export default {
  name: "Collect",
  components: {
    collectAdd
  },
  data() {
    return {
      addOpen: false,
      addRow: null,
      detailCollectId: null,
      //列表回收数量
      listNumber: null,
      /*门店回收列表*/
      storeList:[],
      /*窗口宽度*/
      diaWidth: "500px",
      /*报价师列表*/
      offerNameOptions: [],
      //时间搜索范围
      createTimeRange: [],
      // 商品信息
      recoveryGoodsList: [],
      // 用户列表
      userList: [],
      // 供应商
      supplierList: [],
      //临时价格
      changePrice: null,
      //供应商列表
      supplierOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 回收管理表格数据
      collectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 详情弹框
      detailOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        collectId: null,
        collectSource: null,
        sourceId: null,
        collectExpress: null,
        status: null,
        createId: null,
        params: {}
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sourceId: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        collectNum: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    listUser({roleKey:'quote'}).then(res => {
      this.offerNameOptions = res.rows;
    })
    this.getList();
    this.getSupplierList();
    this.getUserList();
  },
  methods: {
    collectPriceTotal(row) {
      if(row.collectPrice == null) {
        return
      }
      let arr = row.collectPrice.split(",");
      let res = 0;
      arr.forEach(a => {
        res += Number(a);
      })
      return res;
    },
    //行合计
    rowTotal(row) {
      let num = 0;
      if(row.price > 0) {
        num += row.price;
      }
      if(row.priceOne > 0) {
        num += row.priceOne;
      }
      if(row.priceTwo > 0) {
        num += row.priceTwo;
      }
      if(row.priceThree > 0) {
        num += row.priceThree;
      }
      if(row.expPrice > 0) {
        num += row.expPrice;
      }
      return num;
    },
    // 报价师字典翻译
    offerNameFormat(row, column) {
      let str = "";
      this.offerNameOptions.forEach(item => {
        if(item.userId === Number(row.offerName))
          str = item.nickName;
      })
      return str;
    },
    /** 创建时间选项*/
    createTimeChange(e) {
      if(e == null) {
        this.$delete(this.queryParams.params, 'createStartTime');
        this.$delete(this.queryParams.params, 'createEndTime');
        return
      }
      this.$set(this.queryParams.params, 'createStartTime', e[0]);
      this.$set(this.queryParams.params, 'createEndTime', e[1]);
    },
    /* 移除价格*/
    removePrice(index) {
      let arr = String(this.form.collectPrice).split(",");
      arr.splice(index, 1);
      this.form.collectPrice = arr.toString() === "" ? null : arr.toString();
    },
    /** 详情导出*/
    handleExportByGoodsList(b) {

      let queryParams = {
        collectId: null,
        sourceId: null
      };
      if(b) {
        if(this.queryParams.sourceId == null) {
          this.msgError("请选择供应商");
          return
        }
        queryParams.sourceId = this.queryParams.sourceId
      }else {
        queryParams.collectId = this.detailCollectId
      }

      this.$confirm('是否确认导出回收商品数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportGoods(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    /** 页面跳转*/
    gotoGoodsPage() {
      this.$router.push({path: '/recovery/goods'})
      this.detailOpen = false;
    },
    /** 前往打印页面*/
    gotoPrinting(row) {
      const url = this.$router.resolve({path: '/printing', query : {collectId: row.collectId}})
      window.open(url.href, '_blank')
    },
    /** 获取商品列表 */
    getRecoveryGoodsList(row) {
      listGoods({collectId: row.collectId}).then(resp => {
        if(row.collectPrice != null) {
          this.recoveryGoodsList = [];
          let priceArr = row.collectPrice.split(",");
          for(let i = 0; i < priceArr.length; i++) {
            for(let j = 0; j < resp.rows.length; j++) {
              if(Number(priceArr[i]) === Number(resp.rows[j].costPrice)) {
                this.recoveryGoodsList.push(resp.rows[j]);
                this.$delete(resp.rows, j);
                break;
              }
            }
          }
        }else {
          this.recoveryGoodsList = resp.rows;
        }
      })
    },
    /** 生成事件*/
    handleAddGoodsList(row) {
      // this.addRow = row;
      // this.addOpen = true;
      this.$confirm('是否确认生成回收商品数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return createGoodsList(row);
      }).then(resp => {
        this.msgSuccess(resp.msg);
        this.getList();
      })
    },
    /**用户格式*/
    userFormatter(userId){
      for(let i = 0; i < this.userList.length; i++) {
        if(userId === this.userList[i].userId) {
          return this.userList[i].nickName;
        }
      }
      return userId + "(删除员工)";
    },
    /** 获取用户列表 */
    getUserList() {
      listUser({}).then(resp => {
        this.userList = resp.rows;
      })
    },
    /**详情页 */
    handleDetail(row) {
      //获取id
      this.getRecoveryGoodsList(row);
      this.detailCollectId = row.collectId;
      this.detailOpen = true;
    },
    /** 供应商格式 */
    supplierFormatter(row)
    {
      /** 二分查找法 时间复杂度 O(log n)*/
      let start = 0;
      let end = this.supplierList.length - 1;
      while (start < end) {
        if((end - start) === 1) {
          if(this.supplierList[start].supplierId === row.sourceId) {
            return this.supplierList[start].supplierName;
          }
          if(this.supplierList[end].supplierId === row.sourceId) {
            return this.supplierList[end].supplierName;
          }
        }
        let index = parseInt((end - start) / 2) + start;
        if(this.supplierList[index].supplierId === row.sourceId) {
          return this.supplierList[index].supplierName;
        }else if(this.supplierList[index].supplierId < row.sourceId) {
          start = index;
        }else {
          end = index;
        }
      }
      return "";
    },
    /**获取供应商列表*/
    getSupplierList() {
      listSupplier({}).then(resp => {
        this.supplierList = resp.rows;
      })
    },
    /**价格组回事件*/
    priceChange() {
      if(this.changePrice <= 0 || this.changePrice == null) {
        this.msgError("请输入正确的价格！")
        return;
      }
      if(this.form.collectPrice == null) {
        this.form.collectPrice = String(this.changePrice);
        this.changePrice = null;
        return ;
      }
      if(this.form.hasGreen === 'y') {
        this.msgError("绿色回收只需要一个总价！")
        return;
      }
      let arr = this.form.collectPrice.split(",");
      if(arr.length < this.form.collectNum) {
        arr.push(this.changePrice);
        this.form.collectPrice = arr.toString();
      }else {
        this.msgError("输入的价格数量超出收货数量!")
      }
      this.changePrice = null;
    },
    /** 远程查询数据 */
    remoteSupplier(e) {
      listSupplier({supplierName: e}).then(resp => {
        this.supplierOptions = resp.rows;
      })
    },
    /** 查询回收管理列表 */
    getList() {
      this.loading = true;
      listCollect(this.queryParams).then(response => {
        this.collectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        collectId: null,
        collectSource: null,
        sourceId: null,
        collectNum: null,
        collectPrice: null,
        collectExpress: null,
        status: 1,
        createId: null,
        createTime: null,
        remark: null,
        offerName: null,
        storeIds: null,
        hasGreen: "n"
      };
      this.supplierOptions = [];
      this.resetForm("form");
      this.diaWidth = "500px"
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      if(this.queryParams.params["createStartTime"] != null) {
        listCollectNumber(this.queryParams).then(resp => {
          this.listNumber = resp.data;
        })
      }else {
        this.listNumber = null;
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.createTimeRange = [];
      this.createTimeChange(null);
      this.handleQuery();
      this.listNumber = null;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.collectId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();

      this.open = true;
      this.title = "添加回收管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const collectId = row.collectId || this.ids
      getCollect(collectId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改回收管理";
        let supplierName = this.supplierFormatter(this.form);
        this.remoteSupplier(supplierName);
        if(this.form.storeIds != null) {
          this.diaWidth = "80%";
          //获取 storeList
          selectListByIds(JSON.parse(this.form.storeIds)).then(resp => {
            this.storeList = resp.data;
          })
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.collectId != null) {
            updateCollect(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCollect(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const collectIds = row.collectId || this.ids;
      this.$confirm('是否确认删除回收管理编号为"' + collectIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCollect(collectIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有回收管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportCollect(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
  }
};
</script>
